<?php
/**
 * Created by PhpStorm.
 * User: timo
 * Date: 2020/3/21
 * Time: 23:25
 */
class Controller_Pc_Api_Standard_Malls extends Controller_Pc_Api_Base
{

    private $_type_id = 21;

    public function before()
    {
        parent::before();
    }

    /**
     * 获取轮播图广告
     */
    public function action_get_rolling_ad()
    {
        $result = DB::select()
            ->from('xcx_ads')
            ->where('prefix', '=', 's_malls_index')
            ->order_by('displayorder', 'asc')
            ->execute()->as_array();
        foreach ($result as &$v) {
            //判断产品类型
            if ($v['typeid'] == 21) {
                $v['url'] = '/stpage/malls/pages/show/show';
                $mod = DB::select('litpic')->from('malls');
            }
            if (!empty($mod)) {
                $row = $mod->where('id', '=', $v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取首页分类栏目
     */
    public function action_get_index_classify()
    {

        $sql = "SELECT * FROM sline_malls_classify WHERE  pid=0 AND isopen=1  ORDER BY IFNULL(displayorder,9999) ASC";
        $res = DB::query(1, $sql)->execute()->as_array();

        $result = array();
        foreach ($res as &$v) {
            $item = array();
            $item['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
            $item['id'] = $v['id'];
            $item['title'] = $v['attrname'];
            $result[] = $item;
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     *获取首页最新栏目
     */
    public function action_get_index_news()
    {
        $p = intval($this->request_body->content->p) or $p = 1;
        $pagesize = intval($this->request_body->content->pagesize) or $pagesize = 4;
        $result = Taglib_Malls::query(array('flag' => 'new', 'row' => $pagesize));
        foreach ($result as &$item) {
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    /**
     *获取首页最热栏目
     */
    public function action_get_index_hots()
    {
        $p = intval($this->request_body->content->p) or $p = 1;
        $pagesize = intval($this->request_body->content->pagesize) or $pagesize = 4;
        $result = Taglib_Malls::query(array('flag' => 'order', 'row' => $pagesize));
        foreach ($result as &$item) {
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取分类页面数据
     */
    public function action_get_malls_classify()
    {

        $result = array();
        $res = Model_Malls_Classify::get_classify_by_pid(0);
        foreach ($res as $v) {
            $title = $v['attrname'];
            $info = Model_Malls_Classify::get_classify_by_pid($v['id']);
            foreach ($info as &$vv) {
                $vv['litpic'] = Model_Api_Standard_System::reorganized_resource_url($vv['litpic']);
            }
            $result[] = array(
                'title' => $title,
                'id' => $v['id'],
                'info' => $info
            );
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    /**
     * 排序
     */
    public function action_xcx_sort_types()
    {
        $sort_types = array(
            array('id' => 0, 'name' => '综合排序'),
            array('id' => 1, 'name' => '价格由低到高'),
            array('id' => 2, 'name' => '价格由高到低'),
            array('id' => 3, 'name' => '销量优先'),
            array('id' => 4, 'name' => '人气推荐'));
        $this->send_datagrams($this->client_info['id'], $sort_types, $this->client_info['secret_key']);
    }

    /**
     * 属性
     */
    public function action_xcx_attr_list()
    {
        $attr_list = DB::select()->from('malls_attr')->where('isopen', '=', 1)->and_where('pid', '=', 0)->execute()->as_array();
        foreach ($attr_list as &$attr) {
            $attr['child_list'] = DB::select()->from('malls_attr')->where('isopen', '=', 1)->and_where('pid', '=', $attr['id'])->execute()->as_array();
        }
        $this->send_datagrams($this->client_info['id'], $attr_list, $this->client_info['secret_key']);
    }

    /**
     * 分类
     */
    public function action_xcx_classify_list()
    {
        $classify_list = DB::select()->from('malls_classify')->where('isopen', '=', 1)->and_where('pid', '=', 0)->execute()->as_array();
        foreach ($classify_list as &$classify) {
            $classify['child_list'] = DB::select()->from('malls_classify')->where('isopen', '=', 1)->and_where('pid', '=', $classify['id'])->execute()->as_array();
        }
        $this->send_datagrams($this->client_info['id'], $classify_list, $this->client_info['secret_key']);
    }

    /**
     * 获取商品列表
     */
    public function action_xcx_search()
    {
        $page_size = 10;
        $page = intval($this->request_body->content->page);

        $params = array();
        $params['classify'] = $this->request_body->content->classify;
        $params['sorttype'] = $this->request_body->content->sort_id;
        $params['attrid'] = $this->request_body->content->attrs;
        $keyword = $this->request_body->content->keyword;

        $out = Model_Api_Standard_Malls::search($params, $keyword, $page, $page_size);
        $result = array(
            'data' => $out['list'],
            'total' => $out['total'],
            'list' => $out['list'],
            'is_finished' => $out['is_finished']
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }


    /**
     * 获取商品数据
     */
    public function action_xcx_get_detail()
    {
        $params['id'] = intval($this->request_body->content->id);
        $productid = intval($this->request_body->content->productid);
        $params['id'] = empty($params['id']) ? $productid : $params['id'];

        $params['userid'] = intval($this->request_body->content->userid);
        if ($params['id']) {
            $result = Model_Api_Standard_Malls::detail($params);

            if (empty($result)) {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询商品失败', '查询商品失败');
            } else {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
    }

    /**
     * 获取购物车数量
     */
    public function action_get_malls_car_num()
    {
        $userid = intval($this->request_body->content->userid);

        $sql = "SELECT COUNT(*) AS num FROM sline_malls_cars WHERE mid={$userid} and type=2";
        $result = DB::query(1, $sql)->execute()->current();

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 加入购物车
     */
    public function action_add_malls_car()
    {
        $userid = intval($this->request_body->content->userid);
        $num = intval($this->request_body->content->num);
        $productid = intval($this->request_body->content->productid);
        $suit_id = intval($this->request_body->content->suit_id);
        $type = intval($this->request_body->content->type);

        $num = $num ? intval($num) : 0;
        $check = Model_Api_Standard_Malls::check_malls_order($productid, $suit_id, $num, $userid,$type);

        if (!$check['status']) {
            $this->send_datagrams($this->client_info['id'], $check, $this->client_info['secret_key']);
        }

        $res = DB::select()->from("malls_cars")
            ->where("malls_id", "=", $productid)
            ->and_where("suit_id", "=", $suit_id)
            ->and_where("mid", "=", $userid)
            ->and_where("type", "=", 2)
            ->execute()
            ->current();

        $data = array(
            'malls_id' => $productid,
            'suit_id' => $suit_id,
            'mid' => $userid,
            'num' => $check['num'],
            'modtime' => time(),
            'title' => $check['info']['title'],
            'litpic' => $check['info']['litpic'],
            'type' => $type
        );
        if (!$res || $type == 1) { // 不存在 或者 为购买
            $data['addtime'] = time();
            list($id, $row) = DB::insert('malls_cars', array_keys($data))->values(array_values($data))->execute();
        } else { // 更新
            $id = $res['id'];
            DB::update('malls_cars')->set($data)
                ->where("malls_id", "=", $productid)
                ->and_where("suit_id", "=", $suit_id)
                ->and_where("mid", "=", $userid)
                ->execute();
        }
        $result = array('status' => true, 'msg' => '加入购物车成功','id'=> $id);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 获取购物车列表
    public function action_get_car_list()
    {
        $userid = intval($this->request_body->content->userid);

        $res = DB::select()->from("malls_cars")->where("mid", "=", $userid)->and_where("type","=",2)->order_by("modtime", 'desc')->execute()->as_array();

        $result = array('status' => true, 'list' => array());
        foreach ($res as &$v) {// 检查购物车里面是否可以下单
            $check = Model_Api_Standard_Malls::check_malls_car($v['malls_id'], $v['suit_id'], $v['num']);
            if ($check['status'] == 201) {
                $result['status'] = false;
                $v['status'] = 201; //失效 需要删除
            } else if ($check['status'] == 202) {
                $result['status'] = false;
                $v['status'] = 202; //库存不足 需要修改库存
            } else {
                $v['status'] = 200;
            }
            $types = Model_Api_Standard_Malls::suit($v['malls_id']);
            $new_type = array();
            foreach ($types as $k => $vv) {
                if ($vv['id'] == $v['suit_id']) {
                    $v['index'] = $k;
                }
                $vv['litpic'] = Common::img($vv['litpic']);
                $type_item = array(
                    'name' => $vv['suitname'],
                    'id' => $vv['id'],
                    'src' => Model_Api_Standard_System::reorganized_resource_url($vv['litpic']),
                    'price' => $vv['price'],
                    'inventory' => $vv['number'], //库存
                    'maxNum' => $vv['max_number'] //限购
                );
                array_push($new_type, $type_item);
            }

            $v['types'] = $new_type;
            $v['number'] = $v['num'];
            $v['price'] = $check['price'];
            $v['suit_name'] = $check['suit_name'];
            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }
        $result['list'] = $res;
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 删除购物车数据
     */
    public function action_del_car_list()
    {
        $userid = intval($this->request_body->content->userid);
        $car_id = Common::remove_xss($this->request_body->content->car_id);

        if (!$car_id || !$userid) {
            $result = array('status' => false, 'msg' => '提交信息有误');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        DB::delete("malls_cars")
            ->where("mid", "=", $userid)
            ->and_where('id', 'in', explode(',', $car_id))
            ->execute();
        $result = array('status' => true, 'msg' => '删除成功');
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 更换购物车商品
     */
    public function action_change_car_list()
    {
        $userid = intval($this->request_body->content->userid);
        $car_id = intval($this->request_body->content->car_id);
        $suit_id = intval($this->request_body->content->suit_id);

        $car_info = DB::select()->from("malls_cars")->where("id","=",$car_id)->and_where("mid","=",$userid)->execute()->current();

        if(!$car_info || $car_info['suit_id'] == $suit_id)
        {
            $result = array('status'=> false,'msg'=> '提交信息有误');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            exit();
        }

        $num = $car_info['num'];
        $productid = $car_info['malls_id'];

        $check = Model_Api_Standard_Malls::check_malls_order($productid, $suit_id, $num, $userid);
        if (!$check['status']) {
            $this->send_datagrams($this->client_info['id'], $check, $this->client_info['secret_key']);
            exit();
        }

        $res = DB::select()->from("malls_cars")
            ->where("malls_id", "=", $productid)
            ->and_where("suit_id", "=", $suit_id)
            ->and_where("mid", "=", $userid)
            ->execute()
            ->current();

        $data = array(
            'malls_id' => $productid,
            'suit_id' => $suit_id,
            'mid' => $userid,
            'num' => $check['num'],
            'modtime' => time(),
            'title' => $check['info']['title'],
            'litpic' => $check['info']['litpic'],
        );
        if (!$res) { // 插入
            $data['addtime'] = time();
            list($id, $row) = DB::insert('malls_cars', array_keys($data))->values(array_values($data))->execute();
        } else { // 更新
            DB::update('malls_cars')->set($data)
                ->where("malls_id", "=", $productid)
                ->and_where("suit_id", "=", $suit_id)
                ->and_where("mid", "=", $userid)
                ->execute();
        }
        DB::delete("malls_cars")->where("id","=",$car_id)->execute();
        $result = array('status'=> true);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取创建购物车中数据
     */
    public function action_get_reserve()
    {
        $userid = intval($this->request_body->content->userid);
        $type = intval($this->request_body->content->type);
        $car_id = Common::remove_xss($this->request_body->content->car_id);

        if(!$car_id || !$userid)
        {
            $result = array('status' => false, 'msg' => '提交信息有误');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            exit();
        }

        $res  = DB::query(1,"select * from sline_malls_cars WHERE mid={$userid} and id in ({$car_id})")->execute()->as_array();
        $new_arr = array();
        foreach($res as $v)
        {
            $check = Model_Api_Standard_Malls::check_malls_car($v['malls_id'], $v['suit_id'], $v['num']);
            if($check['status'] == 200 || $check['status'] == 202 )
            {
                $v['price'] = $check['price'];
                $v['suit_name'] = $check['suit_name'];
                if($check['status'] == 202)
                {
                    $v['num'] = $check['num'];
                }
                $v['litpic'] = Common::img($v['litpic']);
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
                $new_arr[]   = $v;
            }


        }
        //查询默认地址
        $defaultaddr=DB::select()->from('member_address')
            ->where('memberid', '=',$userid)
            ->and_where('is_default','=',1)
            ->execute()
            ->current();
        $re=['result'=>$new_arr,'defaultaddr'=>$defaultaddr];
        $this->send_datagrams($this->client_info['id'], $re, $this->client_info['secret_key']);
    }


    // 计算运费
    public function action_get_express_fee()
    {
        $userid = intval($this->request_body->content->userid);
        $address_id = intval($this->request_body->content->address_id);
        $car_id = Common::remove_xss($this->request_body->content->car_id);

        if(!$car_id || !$userid)
        {
            $result = array('status' => false, 'msg' => '提交信息有误');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            exit();
        }

        $res  = DB::query(1,"select * from sline_malls_cars WHERE mid={$userid} and id in ({$car_id})")->execute()->as_array();
        $new_arr = array();
        $express_fee = 0;
        foreach($res as $v)
        {
            $check = Model_Api_Standard_Malls::check_malls_car($v['malls_id'], $v['suit_id'], $v['num']);
            if($check['status'] == 200 || $check['status'] == 202 )
            {
                if($check['status'] == 202)
                {
                    $v['num'] = $check['num'];
                }

                $suit = $check['suit_info'];
                if(!empty($suit['freightid']))
                {
                    $plan_info = null;
                    $plan_info = Model_Express_Plan::get_plan($suit['freightid'],$address_id);

                    if($plan_info['status']==0)
                    {

                        $result = array('status'=> false,'msg'=> $plan_info['msg']);
                        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
                        exit();
                    }
                    else
                    {
                        // 计算运费
                        $express_price = Model_Express_Plan::get_freight_price($check['suit_info'],$plan_info['data'],$v['num']);
                        $express_fee = $express_fee + floatval($express_price);
                    }
                }
            }
        }
        $this->send_datagrams($this->client_info['id'], $new_arr, $this->client_info['secret_key']);
    }


    // 获取会员收货地址列表
    public function action_xcx_address_list()
    {
        $userid = intval($this->request_body->content->userid);
        $page = intval($this->request_body->content->page);
        $page = $page < 1 ? 1 : $page;
        $page_size = 10;
        $list = DB::select()->from('member_address')->where('memberid', '=',$userid)->order_by('is_default','desc')->order_by('id','desc')->limit($page_size)->offset(($page - 1) * $page_size)->execute()->as_array();
        $this->send_datagrams($this->client_info['id'], array('list'=>$list,'is_finished'=>true), $this->client_info['secret_key']);
    }

    // 删除会员收货地址信息
    public function action_xcx_address_del()
    {
        $userid = intval($this->request_body->content->userid);
        $id = intval($this->request_body->content->id);
        $del = DB::delete('member_address')->where('memberid', '=',$userid)->and_where('id','=',$id)->execute();
        $result = $del? array('status'=>true):array('status'=>false);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 获取会员收货地址信息
    public function action_xcx_address_info()
    {
        $userid = intval($this->request_body->content->userid);
        $addressid = intval($this->request_body->content->addressid);
        $result = DB::select()->from('member_address')->where('memberid', '=',$userid)->and_where('id','=',$addressid)->execute()->current();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 保存会员地址
    public function action_xcx_address_save()
    {
        $userid = intval($this->request_body->content->userid);
        $addressid = intval($this->request_body->content->addressid);
        $city =  $this->request_body->content->city;
        $address =  $this->request_body->content->address;
        $phone =  $this->request_body->content->phone;
        $receiver =  $this->request_body->content->receiver;
        $postcode =  $this->request_body->content->postcode;
        $province =  $this->request_body->content->province;
        $is_default =  $this->request_body->content->is_default;

        if(empty($userid))
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'会员不能为空'), $this->client_info['secret_key']);
            return;
        }

        $model = ORM::factory('member_address')->where('memberid','=',$userid)->and_where('id','=',$addressid)->find();
        $model->memberid = $userid;
        $model->province = $province;
        $model->city = $city;
        $model->address = $address;
        $model->phone = $phone;
        $model->receiver = $receiver;
        $model->postcode = $postcode;
        $model->is_default = $is_default;
        $model->save();
        if($model->saved())
        {
            if($model->is_default==1)
            {
                DB::update('member_address')->set(array('is_default'=>0))->where('memberid','=',$userid)->and_where('id','!=',$model->id)->execute();
            }
            $this->send_datagrams($this->client_info['id'], array('status'=>true), $this->client_info['secret_key']);

        }
        else
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'保存失败'), $this->client_info['secret_key']);
        }


    }

    //获取所有的城市
    public function action_xcx_address_city()
    {
        $list = DB::select()->from('express_destination')->where('pid','=',0)->execute()->as_array();
        foreach($list as &$v)
        {
            $v['children'] = DB::select()->from('express_destination')->where('pid','=',$v['id'])->execute()->as_array();
        }
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    // 检查快递地址
    public function action_xcx_check_address()
    {
        $car_id = intval($this->request_body->content->car_id);
        $addressid = intval($this->request_body->content->address_id);
        $userid = intval($this->request_body->content->userid);

        $param = array(
            'car_id'=> $car_id,
            'addressid'=> $addressid,
            'userid'=> $userid
        );
        $result = Model_Api_Standard_Malls::get_express_fee($param);
        $this->send_datagrams($this->client_info['id'],$result, $this->client_info['secret_key']);
    }

    /**
     * @function 创建订单
     * @return null
     */
    public function action_xcx_order_submit()
    {
        $userid = intval($this->request_body->content->userid);
        $linkman = $this->request_body->content->linkman;
        $linktel = $this->request_body->content->linktel;
        $linkemail = $this->request_body->content->linkemail;
        $remark = $this->request_body->content->remark;

        $car_id = $this->request_body->content->car_id;
        $address_id = $this->request_body->content->address_id;

        $validataion = Validation::factory(array('linkman'=>$linkman,'linktel'=>$linktel));
        $validataion->rule('linktel', 'not_empty');
        $validataion->rule('linktel', 'phone');
        $validataion->rule('linkman', 'not_empty');

        try{
            if (!$validataion->check())
            {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }

            if (!Model_Member_Address::check_address_id($userid, $address_id)) {
                throw new Exception('收货地址有误请重新选择');
            }
            // 获取运费
            $param = array(
                'car_id'=> $car_id,
                'addressid'=> $address_id,
                'userid'=> $userid
            );
            $express_fee = Model_Api_Standard_Malls::get_express_fee($param);
            if(!$express_fee['status'])
            {
                throw new Exception('所选收货地址不在配送范围，请重新选择');
            }

            $express_total_price = $express_fee['price'];
            $auto_close_time = 0;
            $title = "";
            $litpic = "";
            // 循环检查
            $res  = DB::query(1,"select * from sline_malls_cars WHERE mid={$userid} and id in ({$car_id})")->execute()->as_array();
            $child_order = array();
            foreach ($res as $v) {
                $suit = ORM::factory('malls_suit')
                    ->where("id=:suitid")
                    ->param(':suitid', $v['suit_id'])
                    ->find()
                    ->as_array();
                if (empty($suit)) {
                    throw new Exception('套餐不存在');
                }

                $suit['price'] = Currency_Tool::price($suit['price']);

                if (!Model_Api_Standard_Malls::check_storage($v['num'],$v['suit_id'])) {
                    throw new Exception('库存不足');
                }
                $product_info = ORM::factory('malls')->where("id", '=', $suit['productid'])->find()->as_array();
                $title = $title ? $title : $product_info['title'];

                $auto_close_time = $auto_close_time == 0 ? $suit['auto_close_time'] : ($auto_close_time < $suit['auto_close_time'] ? $auto_close_time : $suit['auto_close_time']);
                $productname = $product_info['title'];
                $litpic = $litpic ? $litpic : $suit['litpic'];
                $child = array(
                    'webid' => 0,
                    'typeid' => $this->_type_id,
                    'productautoid' => $product_info['id'],
                    'productaid' => $product_info['aid'],
                    'productname' => $productname,
                    'litpic' => $suit['litpic'],
                    'price' => $suit['price'],
                    'childprice' => 0,
                    'jifentprice' => 0,
                    'jifenbook' => 0,
                    'jifencomment' => 0,
                    'paytype' => 1,
                    'dingjin' => '',
                    'usedate' =>'',
                    'departdate' => '',
                    'addtime' => time(),
                    'memberid' => $userid,
                    'dingnum' => $v['num'],
                    'childnum' => 0,
                    'oldprice' => 0,
                    'oldnum' => 0,
                    'suitid' => $v['suit_id'],
                    'status' => 1,
                    'source' => 3,//来源小程序
                    'suit_name'=> $suit['suitname']
                );
                array_push($child_order,$child);
            }

            $p_num = count($res);
            $title = $title."等".$p_num.'件商品';

            if($auto_close_time)
            {
                $auto_close_time = $auto_close_time + time();
            }

            $ordersn = Product::get_ordersn($this->_type_id);
            $arr = array(
                'ordersn' => $ordersn,
                'webid' => 0,
                'typeid' => $this->_type_id,
                'productautoid' => 1,
                'productaid' => 1,
                'productname' => $title,
                'litpic' => $litpic,
                'price' => $express_total_price,
                'childprice' => 0,
                'jifentprice' => 0,
                'jifenbook' => 0,
                'jifencomment' => 0,
                'paytype' => 1,
                'dingjin' => '',
                'usedate' =>'',
                'departdate' => '',
                'addtime' => time(),
                'memberid' => $userid,
                'dingnum'  => 1,
                'childnum' => 0,
                'oldprice' => 0,
                'oldnum'  => 0,
                'linkman' => $linkman,
                'linktel' => $linktel,
                'linkemail'=>$linkemail,
                'haschild'=> 1,
                'suitid' => 0,
                'remark' => $remark,
                'status' => 1,
                'source' => 3,//来源小程序,
                'usejifen'  => 0,
                'needjifen' => 0,
                'receiver_address_id' => $address_id,
                'express_total_price' => 0,
                'auto_close_time'     => $auto_close_time, //自动关闭订单时间
            );

            //添加主订单
            if (St_Product::add_order($arr,'Model_Malls',$arr))
            {
                $orderInfo = Model_Member_Order::order_info($ordersn);

                foreach ($child_order as $vv)
                {
                    $child_ordersn = Product::get_ordersn($this->_type_id);
                    // 添加子订单
                    $child_arr = $vv;
                    $child_arr['ordersn'] = $child_ordersn;
                    $child_arr['pid']     = $orderInfo['id'];
                    St_Product::add_order($child_arr,'Model_Malls',$child_arr);
                }

                //订单结算信息表数据更新
                Model_Member_Order_Compute::update($ordersn);
                St_Product::event($ordersn);
                // 删除购物车
                DB::delete('malls_cars')->where('mid',"=",$userid)->and_where('id', 'in', DB::expr("({$car_id})"))->execute();
                $this->send_datagrams($this->client_info['id'], array('status'=>true,'order'=>$orderInfo['id']), $this->client_info['secret_key']);
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], array('status'=>false), $this->client_info['secret_key']);
            }
        }
        catch (Exception $excep)
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>$excep->getMessage()), $this->client_info['secret_key']);
        }
    }



    /**
     * @function 写入主订单
     * @param $arr
     * @return bool|int
     */
    public static function add_order($arr)
    {
        $flag = 0;
        $model = ORM::factory('member_order');
        if (is_array($arr))
        {
            $db = Database::instance();
            $db->begin();
            try
            {

                foreach ($arr as $k => $v)
                {
                    $model->$k = $v;
                }
                $model->save();
                $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollback();
                Request::$current->redirect('error/tips?msg=' . $e->getMessage());
                return;
            }

            Model_Message::add_order_msg($model->as_array());
            //订单监控
            $detectresult = Model_Member_Order::detect($arr['ordersn']);
            if ($detectresult !== true)
            {
                return false;
            }
            //订单监控
            $detectresult = Model_Member_Order::detect($arr['ordersn']);
            //返回状态
            $flag = 1;
        }
        return $flag;
    }

    // 获取订单列表
    public function  action_xcx_get_order_list()
    {
        $userid = intval($this->request_body->content->userid);
        $status = intval($this->request_body->content->status);
        $page = intval($this->request_body->content->page);
        $pagesize = intval($this->request_body->content->pagesize);

        // 获取订单数据
        if(!$userid)
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'list'=> array(),'msg'=>'用户信息有误'), $this->client_info['secret_key']);
        }

        $param = array(
            'userid'=> $userid,
            'status'=> $status,
            'page'=> $page,
            'pagesize'=> $pagesize,
        );
        $result = Model_Api_Standard_Malls::get_order_list($param);

        $this->send_datagrams($this->client_info['id'], array('status'=>true,'list'=>$result), $this->client_info['secret_key']);
    }


    // 订单详情
    public function action_xcx_get_order_detail()
    {
        $userid = intval($this->request_body->content->userid);
        $id = intval($this->request_body->content->id);

        //主订单
        $ordersn = DB::select('ordersn')->from('member_order')->where('id','=',$id)->execute()->get('ordersn');
        $row = Model_Member_Order::order_info($ordersn, $userid);

        if(empty($row)){
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'订单不存在'), $this->client_info['secret_key']);
            return;
        }

        // 子订单
        $child = DB::select("ordersn")->from("member_order")->where("pid","=",$id)->execute()->as_array();
        $c_arr = array();
        foreach ($child as $vv)
        {
            $item = array();
            $c_row = Model_Member_Order::order_info($vv['ordersn'], $userid);
            //封面图
            $item['litpic'] = Common::img($c_row['litpic']);
            $item['num'] = $c_row['dingnum'];
            $item['price'] = $c_row['price'];
            $item['ispinlun'] = $c_row['ispinlun'];
            $item['status'] = $c_row['status'];
            $item['id'] = $c_row['id'];
            $item['productautoid'] = $c_row['productautoid'];
            $item['subname'] = $c_row['suit_name'];
            $item['productname'] = $c_row['productname'];

            array_push($c_arr,$item);
        }

        $row['payprice'] = Currency_Tool::price($row['payprice']);
        $totalprice = $row['totalprice'] - $row['price']; // 扣减运费
        $row['totalprice'] = Currency_Tool::price($totalprice);
        $row['c_order'] = $c_arr;
        $status=DB::select()->from('malls_order_status')->where('status','=',$row['status'])->and_where('is_show','=',1)->execute()->current();
        $row['statusname']=$status['status_name'];

        if($row['receiver_address_id'])
        {
            $receiver_address = DB::select()->from('member_address')->where('id','=',$row['receiver_address_id'])->execute()->current();
            $row['receiver_address'] =  $receiver_address;

        }
        $row = Pay_Online_Refund::get_refund_info($row);

        if($row['status'])
        {
            // 转换自动关闭时间
            $auto_close_time = $row['auto_close_time'];
            $auto_close_time = $auto_close_time - time();
            if($auto_close_time > 0)
            {
                $day = floor($auto_close_time / 86400);
                $hour = floor(($auto_close_time - $day * 86400) / 3600);
                $minute = floor(($auto_close_time - $day * 86400 - 3600 * $hour)/60);

                $day_s = $day > 0 ? $day .'天' : '';
                $hour_s = $hour > 0 ? $hour .'小时' : '';
                $minute_s = $minute > 0 ? $minute .'分' : '';

                $auto_close_str = $day_s.$hour_s.$minute_s;
                $row['auto_close_str'] = $auto_close_str;
            }
        }


        //快递信息
        $express_info = DB::select("express_company_name","express_code","end_time")->from("malls_order_express")->where("ordersn","=",$row['ordersn'])->execute()->current();
        if($express_info)
        {
            $auto_time = $express_info['end_time'] - time();
            if($auto_time > 0)
            {
                $day = floor($auto_time / 86400);
                $hour = floor(($auto_time - $day * 86400) / 3600);
                $minute = floor(($auto_time - $day * 86400 - 3600 * $hour)/60);

                $day_s = $day > 0 ? $day .'天' : '';
                $hour_s = $hour > 0 ? $hour .'小时' : '';
                $minute_s = $minute > 0 ? $minute .'分' : '';

                $auto_str = $day_s.$hour_s.$minute_s;
                $express_info['auto_str'] = $auto_str;
            }
            else
            { // 自动收货

            }
        }

        $suit = Model_Api_Standard_Malls::suit_info($row['suitid']);
        $suit['express_template'] = DB::select()->from('express_template')->where('id','=',$suit['freightid'])->execute()->current();
        $row['suit'] = $suit;
        $row['express'] = $express_info;
        $row['addtime_fmt'] = date('Y-m-d H:i:s',$row['addtime']);
        $row['paytime'] = $row['paytime'] ? date('Y-m-d H:i:s',$row['paytime']) : '';
        $this->send_datagrams($this->client_info['id'], $row, $this->client_info['secret_key']);
    }

    // 取消订单
    public function action_cancel_order()
    {
        $ordersn = Common::remove_xss($this->request_body->content->ordersn);
        $userid = intval($this->request_body->content->userid);
        //检查订单状态
        $info = DB::select()->from("member_order")->where("ordersn","=",$ordersn)->and_where("memberid","=",$userid)->execute()->current();
        if($info)
        {

            if($info['status'] != 0 && $info['status'] != 1)
            {
                $result = array('status'=> false,'msg'=> '订单信息有误');
            }
            else
            { // 取消订单
                $result = DB::update("member_order")->set(array('status'=> 3))->where("ordersn","=",$ordersn)->execute();
                if($result)
                { // 取消子订单
                    DB::update("member_order")->set(array('status'=> 3))->where("pid","=",$info['id'])->execute();
                    $result = array('status'=> true,'msg'=> '取消成功');
                }
                else
                {
                    $result = array('status'=> false,'msg'=> '取消订单失败');
                }
            }
        }
        else
        {
            $result = array('status'=> false,'msg'=> '订单信息有误');
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    // 获取快递信息
    public function action_xcx_get_order_express()
    {
        $id = intval($this->request_body->content->id);
        $userid = intval($this->request_body->content->userid);

        // 检查是否是当前人员的订单
        $res = DB::select()->from("member_order")
            ->where("memberid","=",$userid)
            ->and_where('id',"=",$id)
            ->execute()->current();
        if(!$res)
        {
            $result = array('status'=> false,'msg'=> '订单信息有误');
        }
        else
        {
            //收货地址
            $phone = "";
            if($res['receiver_address_id'])
            {
                $receiver_address = Model_Member_Address::get_address_info($res['receiver_address_id']);
                $phone = $receiver_address['phone'];
            }
           // 检查是否发送快递
            $ordersn = $res['ordersn'];
            $express = DB::select()->from("malls_order_express")
                ->where("ordersn","=",$ordersn)
                ->order_by("add_time","DESC")
                ->execute()->current();
            if(!$express)
            {
                $result = array('status'=> false,'msg'=> '没有找到物流信息');
            }
            else
            {

                $data = array(
                    'number'=> $express['express_code'],
                    'phone' => $phone,
                    'company'=> $express['express_company_code'],
                );
                //直接获取
                $result = Model_Malls_Express::express_poll($data);
                // 订单支付时间
                $pay_time = '';
                if($res['paytime'])
                {
                    $pay_time = array(
                        'day' => date("m-d",$res['paytime']),
                        'hour' => date("H:i",$res['paytime'])
                    );
                }
                $result['pay_time'] = $pay_time;
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 确认收货 实际为已完成
    public function action_xcx_express_confirm ()
    {
        $ordersn =$this->request_body->content->ordersn;
        $userid = intval($this->request_body->content->userid);

        $model = ORM::factory('member_order')->where('ordersn','=',$ordersn)->and_where('memberid','=',$userid)->find();

        if(!$model->loaded() || $model->status!='8' || $model->typeid!='21')
        {
            $result = array('status' => false, 'message' => __('错误'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            return;
        }

        $model->status = 5;
        $model->save();
        if($model->saved())
        {
            $model->reload();
            $info = $model->as_array();
            Model_Malls_Order::back_order_status_changed(8, $info, 'Model_Malls');
            $result=array('status' => true, 'message' => __('已完成'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
    }

}